<template>
  <div class="app-container">
    <div class="customContainer">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-date-picker
            v-model="pickerDate"
            value-format="yyyy.MM.dd"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="仓库" v-model="formInline.house_id">
            <el-option
              v-for="item in house_list"
              :key="item.house_id"
              :label="item.name"
              :value="item.house_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="选择类型" v-model="formInline.species" filterable>
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="订单状态:" v-model="formInline.status" filterable>
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.no" placeholder="请输入采购单号" @keyup.enter.native="searchClick"></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table
        highlight-current-row
        :data="list"
        border
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="36"></el-table-column>
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status==0">待审核</span>
            <span v-if="scope.row.status==1">待确认</span>
            <span v-if="scope.row.status==2">待发货</span>
            <span v-if="scope.row.status==3">部分收货</span>
            <span v-if="scope.row.status==4">订单完结</span>
            <span v-if="scope.row.status==5">收货完成</span>
            <span v-if="scope.row.status==6">订单取消</span>
            <span v-if="scope.row.status==8">待收货</span>
            <span v-if="scope.row.status==9">申请退货中</span>
            <span v-if="scope.row.status==10">退货中</span>
            <span v-if="scope.row.status==11">退货完成</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="下单时间" prop="creat_time"></el-table-column>
        <el-table-column align="center" label="采购订单编号">
          <template slot-scope="scope">
            <el-button
              @click="get_order_info(scope.row.id,scope.$index,scope.row.status)"
              type="text"
              size="small"
            >{{scope.row.order_id}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="采购渠道">
          <template slot-scope="scope">{{scope.row.type==1 ? '供应商' :'中央仓'}}</template>
        </el-table-column>
        <el-table-column align="center" label="到货差额">
          <template
            slot-scope="scope"
          >{{scope.row.arrive_accessories - scope.row.total_accessories}}</template>
        </el-table-column>
        <el-table-column align="center" label="入库时间" prop="company_name">
          <template
            slot-scope="scope"
          >{{scope.row.update_time=='0'?'----.--.--':(scope.row.update_time)}}</template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark"></el-table-column>
      </el-table>
    </div>
    <!-- 采购入库弹框 -->
    <el-dialog
      width="80%"
      :close-on-click-modal="false"
      class="dialog_table"
      title="采购入库"
      :visible.sync="detail_dialog"
    >
      <div class="dialogInContainer" v-loading="dialogLoading">
        <el-table
          highlight-current-row
          :data="infolist"
          border
          size="small"
          @selection-change="detailSelection"
        >
          <el-table-column type="selection" width="36"></el-table-column>
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              <span class="indexColor">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="图片" width="70">
            <template slot-scope="scope">
              <img :src="scope.row.thumb" width="50" height="50" alt />
            </template>
          </el-table-column>
          <el-table-column align="center" label="物品名称" prop="accessories_name"></el-table-column>
          <el-table-column align="center" label="物品编号" prop="accessories_id"></el-table-column>
          <el-table-column align="center" label="类别" prop="type_name"></el-table-column>
          <el-table-column align="center" label="订单数" prop="total_num"></el-table-column>
          <el-table-column align="center" label="累计到货数" prop="arrive_num"></el-table-column>
          <el-table-column align="center" label="本次到货数">
            <template slot-scope="scope">
              <el-input
                type="number"
                onmousewheel="return false;"
                v-model="scope.row.now_arrive_num"
                :disabled="isDisabled||scope.row.is_del*1>0||scope.row.all_arrive"
                placeholder="数量"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="差异">
            <template slot-scope="scope">
              <span
                :class=" scope.row.now_arrive_num*1+scope.row.arrive_num*1 -scope.row.total_num*1==0?'':'danger'"
              >
                {{scope.row.now_arrive_num*1+scope.row.arrive_num*1
                -scope.row.total_num*1 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="审核结果">
            <template slot-scope="scope">
              <span v-if="scope.row.status==4">结束</span>
              <span v-else-if="scope.row.is_del==0&&scope.row.status==0">审核中</span>
              <span v-else-if="scope.row.is_del==0&&scope.row.status!=0">通过</span>
              <span v-else class="danger">未通过</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注">
            <template slot-scope="scope">
              物品部:{{scope.row.remark_g}}
              <br />
              采购部:{{scope.row.remark_p}}
            </template>
          </el-table-column>
        </el-table>
        <!-- 自定义底部 -->
        <br />
        <div class="bottom_box">
          <el-button
            v-if="infoSelection.length>0 && !isDisabled"
            :disabled="isDisabled"
            size="small"
            type="primary"
            @click="allArriveClick()"
          >无差异到货</el-button>
          <el-button
            v-if="infoSelection.length>0 && !isDisabled"
            :disabled="isDisabled"
            size="small"
            type="primary"
            @click="resetClick()"
          >重置</el-button>
          <el-button
            class="pull-right"
            :disabled="isDisabled"
            size="small"
            type="primary"
            :loading="btnLoding"
            @click="saveClick()"
          >确认提交</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
      <div class="pull-right">
        <el-button
          :disabled="exportForm.length==0"
          type="primary"
          size="small"
          @click="exportClick()"
          :loading="exportLoading"
        >
          采购单导出
          <count-down ref="cd" />
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  house,
  getList,
  getPage,
  getExport,
  getinfoList,
  save,
  get_goods_type,
} from "@/api/storage_control/pj_purchase_in.js";
import { pickerOptionsF, pickerDateF, optionMaxTime } from "@/utils";
export default {
  data() {
    return {
      exportLoading: false,
      btnLoding: false,
      dialogLoading: false,
      type_list: null,
      status: [
        { id: -1, name: "全部" },
        { id: 0, name: "待审核" },
        { id: 1, name: "待确认" },
        { id: 2, name: "待发货" },
        { id: 3, name: "部分收货" },
        { id: 4, name: "订单完结" },
        { id: 5, name: "收货完成" },
        { id: 6, name: "订单取消" },
        { id: 8, name: "待收货" },
        { id: 9, name: "申请退货中" },
        { id: 10, name: "退货中" },
        { id: 11, name: "退货完成" },
      ],
      currentPage: 1,
      totalDataNumber: 0,
      logistics_company: "",
      logistics_no: "",
      editId: "",
      editIndex: "",
      stateName: "",
      formInline: {
        house_id: 0,
        species: "",
        no: "",
        start: "",
        end: "",
        status: -1,
      },
      detail_dialog: false,
      infolist: [],
      house_list: [],
      list: null,
      saveForm: {
        order_id: this.editId,
        data: [],
      },
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateF(),
      exportForm: "",
      infoSelection: [],
      isDisabled: false,
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.type_list) {
        vm.getGoods();
        vm.gethouse();
      }
    });
  },
  // created() {
  //     this.gethouse();
  //     this.getGoods();
  // },
  methods: {
    getGoods() {
      get_goods_type({ category_id: this.$route.meta.id }).then((response) => {
        response.forEach((item) => {
          if (item.name == "配件类物品") {
            item.id = 1;
          } else if (item.name == "财务类物品") {
            item.id = 2;
          } else if (item.name == "其他类物品") {
            item.id = 3;
          }
        });
        this.type_list = response;
        this.formInline.species = response.length > 0 ? response[0].id : "";
      });
    },
    resetClick() {
      this.infoSelection.forEach((val1) => {
        this.infolist.forEach((val2) => {
          if (val1.id == val2.id) {
            val2.now_arrive_num = "";
          }
        });
      });
    },
    allArriveClick() {
      this.infoSelection.forEach((val1) => {
        this.infolist.forEach((val2) => {
          if (val1.id == val2.id) {
            val2.now_arrive_num = 0;
            val2.now_arrive_num =
              val2.total_num * 1 - val2.arrive_num * 1 == 0
                ? ""
                : val2.total_num * 1 - val2.arrive_num * 1;
          }
        });
      });
    },
    detailSelection(val) {
      this.infoSelection = val;
    },

    saveClick() {
      let flat = true;
      this.saveForm.data = [];
      // 过滤掉全部到货的数组
      let new_infolist = this.infolist.filter(function (item) {
        return item.total_num != item.arrive_num;
      });
      this.infolist.forEach((val, index) => {
        if (
          (!val.all_arrive && val.is_del == 0 && val.now_arrive_num == "") ||
          (!val.all_arrive && val.is_del == 0 && val.now_arrive_num == null)
        ) {
          return;
        } else {
          if (
            Number(val.arrive_num) + Number(val.now_arrive_num) >
            Number(val.total_num)
          ) {
            flat = false;
            // return;
          } else {
            this.saveForm.data.push({
              accessories_id: val.accessories_id,
              arrive_num: val.now_arrive_num * 1,
              look_money: val.money_sell,
            });
          }
        }
      });
      if (flat == false) {
        this.$message({ type: "error", message: "到货数不能大于订单数!" });
        return;
      }
      if (this.saveForm.data.length == this.infolist.length) {
        this.$confirm("此操作提交, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.btnLoding = true;
          save(this.saveForm)
            .then((response) => {
              this.$message({
                type: response.code == 1 ? "success" : "error",
                message: response.message,
              });
              if (response.code == 1) {
                this.btnLoding = false;
                this.detail_dialog = false;
                this.searchClick();
              }
            })
            .catch(() => {
              this.btnLoding = false;
            });
        });
      } else {
        this.$message({ type: "error", message: "请将所有信息填写完整!" });
        return;
      }
    },
    handleSelectionChange(val) {
      this.exportForm = val;
      console.log(this.exportForm);
    },
    // 导出
    exportClick() {
      const idArr = [];
      this.exportForm.forEach(function (val, index) {
        idArr.push(val.id);
      });
      // if (idArr.length > 1) {
      //     this.$message({ type: 'error', message: '采购入库导出目前仅支持“单选”' })
      //     return;
      // }
      getExport({ type: 1, order_id: idArr.join(",") });
      this.exportLoading = true;
      this.$refs.cd.countDownF(30).then(() => {
        this.exportLoading = false;
      });
    },
    // 打开订单详情
    get_order_info(id, index, status) {
      this.dialogLoading = true;
      this.detail_dialog = true;
      this.saveForm.order_id = id;
      getinfoList({ order_id: id }).then((response) => {
        response.forEach((val) => {
          val.all_arrive = val.total_num == val.arrive_num ? true : false;
        });
        this.infolist = response;
        if (response[0].status == 3 || response[0].status == 8) {
          this.isDisabled = false;
        } else {
          this.isDisabled = true;
        }
        this.dialogLoading = false;
      });
    },
    gethouse() {
      house().then((response) => {
        this.house_list = response;
      });
    },
    searchClick() {
      optionMaxTime(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start = this.pickerDate[0];
        this.formInline.end = this.pickerDate[1];
        this.fetchData();
      });
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then((response) => {
          this.totalDataNumber = response.page * 20;
          getList(this.formInline).then((response) => {
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch((res) => {
          this.listLoading = false;
        });
      // console.log(list);
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then((response) => {
        this.list = response;
        this.listLoading = false;
      });
    },
  },
};
</script>